package com.yhxd.modular.reference.api;

import com.yhxd.modular.reference.entity.PublicFile;
import com.yhxd.modular.reference.service.PublicFileService;
import io.swagger.annotations.Api;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.net.URLEncoder;

@Controller
@RequestMapping(value = "/api/pub")
@Api
public class ApiPublicController {

    @Autowired
    private PublicFileService publicFileService;

    /**
     * 下载
     *
     * @return
     */
    @GetMapping(value = "/downFile/{id}")
    @ResponseBody
    public void downFile(HttpServletResponse response, @PathVariable("id") Long id) {
        try {
            PublicFile publicFile = this.publicFileService.findById(id);
            FileInputStream fis = new FileInputStream(publicFile.getLocalpath());
            ServletOutputStream out = response.getOutputStream();

            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(publicFile.getFileName() + "." + publicFile.getSuffix(), "UTF-8"));
            response.setHeader("Content-Length", String.valueOf(fis.available()));

            IOUtils.copy(fis, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
